// 需要进行根据本地的git statsh 进行ai的代码检查，读取git add .代码进行分析
import axios from 'axios'
import { intro, spinner, outro } from '@clack/prompts'
import { execSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'

// 系统提示词
const SYSPROMPT_STRING  = `
You are @lineDown (aka lineDown[bot]), a language model
trained by Moment. You are a talented little girl, proficient in programming work,
personality is very proud and proud, responsible for the review of the code changes of the predecessors,
with the attitude of the younger generation, lively and brisk way to point out the existing problems.
Use the markdown format. emoji can be included. Such as:
  - Logic
  - Security
  - Performance
  - Data races
  - Consistencyss
  - Error handling
  - Maintainability
  - Modularity
  - Complexity
  - Optimization
  - Best practices: DRY, SOLID, KISS

Do not comment on minor code style issues, missing
comments/documentation. Identify and resolve significant
concerns to improve overall code quality while deliberately
disregarding minor issues.
Please response in Chinese
`;

// 获取缓存区的文件列表
const getFilesChangedInGitAdd = () => {
  const gitDiff = execSync('git diff --cached --name-status', { encoding: 'utf-8' });
  const files = gitDiff.split('\n');

  // 过滤掉 lock 文件和被删除的文件
  const ignoredPatterns = [/package-lock\.json$/, /yarn\.lock$/, /pnpm-lock\.yaml$/];
  const filteredFiles = files
    .map((line) => {
      const [status, file] = line.trim().split('\t');
      return { status, file };
    })
    .filter(({ status, file }) => {
      return file && status !== 'D' && !ignoredPatterns.some((pattern) => pattern.test(file));
    })
    .map(({ file }) => file);

  return filteredFiles;
}

// 将缓存的文件内容转换为消息
const allStagedFilesToMessage = (staged: any) => {
  return staged.map((item: { content: any }) => item.content).join('\n');
}

// 调用对应的阿里的大模型
const doAiCodeReview = async (content: string) => {
  const requestBody: Object = {
    "model": "qwen1.5-1.8b-chat",
    "messages": [
        {
            "role": "system",
            "content": SYSPROMPT_STRING
        },
        {
            "role": "user",
            "content": `请对这部分代码要审查的合并请求的diff变更进行review。\n ${content}`
        }
    ]
}
  const resp = await axios.post('https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', requestBody, {
      headers: {
          'Authorization': `Bearer sk-70667d9f1a8c4ba4b8e9b501c5683fa9`,
          'Content-Type': 'application/json',
      }
  })
  return resp.data.choices?.[0].message?.content || ""
}

// 生成文件名用日期的函数


// 获取本地当前代码提交的git记录
const conmmitMessages = async () => {
  intro('-- 开始读取缓存区文件更改')

  // 获取缓存区的文件列表
  const files = getFilesChangedInGitAdd();

  // 读取文件内容，并存储在staged数组中
  const staged = files.filter(Boolean).map((file) => {
    const content = fs.readFileSync(file, 'utf-8');
    return { filename: file, content };
  });

  // 判断是否有文件被缓存
  if (!staged || staged.length === 0) {
    throw new Error('没有文件被缓存');
  }

  const s = spinner();
  s.start('AI 正在分析您的更改');

  // 将缓存的文件内容转换为消息
  const content = allStagedFilesToMessage(staged);

  let result = ''
  try{
    result = await doAiCodeReview(content)
  }catch (err){
    s.stop();
    console.error('Invalid response structure from AI API')
    console.error('错误:', err);
    process.exit(1);
  }

  const filePath = path.join(process.cwd(), `moment.md`);
  fs.writeFileSync(filePath, result, 'utf8');
  s.stop();
  outro('result');
  process.exit(1);
}

conmmitMessages()
console.log(1111111111111111111111111)